#pragma once

#include <winsock2.h>
#include "Message.h"
#include <cstdio>
class HandleRead
{
public:
	HandleRead();
	~HandleRead();

	int handle_read_fd(SOCKET client);

private:
	// first cache is net stack setting
	// second buffer for net data,to save every time read data from recv to clear net stack cache
	char receive_buffer[1024 * 10];
	unsigned int buffer_tail = 0;
};

HandleRead::HandleRead()
{
}

HandleRead::~HandleRead()
{
}



int HandleRead::handle_read_fd(SOCKET client) {

	char data[1024 * 64] = {};
	unsigned int cur_index = 0;

	// 5. get cmd from client
	int len = recv(client, data, 1024 * 64, 0);
	if (len < 1) {
		printf("data_type len < 1\n");
		closesocket(client);
		return -1;
	}

	memcpy(&receive_buffer[buffer_tail], data, len);
	buffer_tail += len;

	if (buffer_tail <= sizeof(DataTypePackage)) {
		return 0;
	}

	while (buffer_tail - cur_index > sizeof(DataTypePackage)) {

		DataTypePackage* dataType;
		dataType = (DataTypePackage*)&receive_buffer[cur_index];

		if (buffer_tail < cur_index + dataType->data_length) {
			break;
		}

		cur_index += dataType->data_length;
		// handle a package data
		switch (dataType->data_type)
		{
		case DataType::LOG_IN: {

			Login* login;
			//char buf[sizeof(Login)];
			// strncpy(buf, &data[sizeof(DataTypePackage)], strlen(buf));

			login = (Login*)&receive_buffer[cur_index];

			char name[] = "zhangsan";
			char password[] = "zs";

			printf("name: %s, passwd: %s\n", login->name, login->passwd);

			if (strcmp(name, login->name) == 0 && strcmp(password, login->passwd) == 0) {

				// login ok
				LoginOk loginOk = {};
				strcpy(loginOk.name, name);

				send(client, (char*)&loginOk, sizeof(loginOk), 0);

			}
			else {
				// login failed
				// login ok
				LoginFailed loginFailed = {};
				int n = strcmp(loginFailed.msg, "login error");
				send(client, (char*)&loginFailed, sizeof(loginFailed), 0);
			}

		}break;
		case DataType::LOG_OUT: {
			// log out
			printf("client logout\n");
			return -1;
		}break;
		case DataType::PERSON_INFO: {
			// request person info
			PersonInfo person = {};
			strcpy(person.name, "zhangsan");
			person.age = 22;

			send(client, (char*)&person, sizeof(person), 0);
			printf("person_info\n");

		}break;
		default: {
			// invalid data
			RequestError requestError = {};
			strcpy(requestError.msg, "invalid cmd");
			return 0;
		}
		}
	}
	if (cur_index != 0) {
		unsigned int new_buffer_tail = 0;
		for (; cur_index < buffer_tail; ) {
			receive_buffer[new_buffer_tail++] = receive_buffer[cur_index++];
		}
		buffer_tail = new_buffer_tail;
	}

	printf("buffer_tail = %u", buffer_tail);
	return 0;
}
